package cetb.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cetb.domain.Address;
import cetb.utils.UIDGenerator;

public class JDBCAddressDAO implements IAddressDAO {

	private IZoneDAO zdao;
	
	public void insert(Connection conn, String aoid, Address address) {
		
		String sql = "INSERT INTO address ( OID, email, fax, phone, street, zipCode, zoneOID) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ";
	    PreparedStatement stmt = null;

	    try {
	        stmt = conn.prepareStatement(sql);    
	        stmt.clearParameters();
	        stmt.setString(1, UIDGenerator.getInstance().getKey());
	        stmt.setString(2, address.getEmail());
	        stmt.setString(3, address.getFax());
	        stmt.setString(4, address.getPhone());
	        stmt.setString(5, address.getStreet());
	        stmt.setInt(6, address.getZipCode());
	      
	        //si la zona no existe, la inserta 
        	String zoid=zdao.selectZoneOID(conn,address.getZone());
        	if(zoid==""){
        		zoid=UIDGenerator.getInstance().getKey();
        		zdao.insert(conn,zoid,address.getZone());
        	}
	           
        	stmt.setString(7, zoid);
	                
	        stmt.executeUpdate(); 
	
	    } catch (SQLException e) {
	    	System.out.println("Message: " + e.getMessage());
	        System.out.println("SQLState: " + e.getSQLState());
	        System.out.println("ErrorCode: " + e.getErrorCode());
	    } finally {
	    	try {
	    		if (stmt != null) {
	    			stmt.close();	                
	    		}
	    	} catch (SQLException e) {
	        
	    	}
	    }
	}
	
	public Address select(Connection conn, String addressOID) {
		Address a=new Address();
        String sql = "SELECT * FROM address WHERE (addressOID = ? ) ";
        PreparedStatement stmt = null;
        ResultSet result = null;

        try {
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, addressOID);

            result = stmt.executeQuery();
            
            if(result.next()){
            	a.setEmail(result.getString("email"));
            	a.setFax(result.getString("fax"));
            	a.setPhone(result.getString("phone"));
            	a.setStreet(result.getString("street"));
            	a.setZipCode(result.getInt("zipcode"));
            	a.setZone(zdao.select(conn,result.getString("zoneOID")));
            }
        
        } catch (SQLException e) {
            System.out.println("Message: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
        } finally {
            try {
                if (result != null) {
                    result.close();
                }

                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
            }
        }

        return a;
    }
	
}
